{include file="layout/layui_header" /}

<!-- 主要内容 -->
<div class="main-content">
    <div class="page-header">
        <h1 class="page-title">角色管理</h1>
        <p class="page-subtitle">管理系统角色和权限分配</p>
    </div>

<style>
.layui-card { 
    margin-bottom: 15px; 
    box-shadow: 0 1px 2px rgba(0,0,0,0.15);
}
.stat-item { 
    text-align: center; 
    padding: 20px; 
}
.stat-value { 
    font-size: 32px; 
    font-weight: bold; 
    color: #01AAED; 
}
.stat-label { 
    margin-top: 8px; 
    color: #666; 
}
.role-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    flex-wrap: wrap;
}
.role-title {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
}
.role-actions {
    display: flex;
    gap: 8px;
}
.search-form {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    margin-bottom: 15px;
    border: 1px solid #e6e8eb;
}
.search-form .layui-form-item {
    margin-bottom: 0;
}
.search-inline {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: end;
}
.search-inline .layui-inline {
    margin: 0;
}
.table-container {
    margin-top: 0;
}
.permission-tree {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e6e8eb;
    padding: 10px;
}
.tree-node {
    padding: 5px 0;
    border-left: 2px solid transparent;
}
.tree-node.parent {
    border-left-color: #01AAED;
    background: #f8f9fa;
}
.tree-node input[type="checkbox"] {
    margin-right: 5px;
}
</style>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 角色统计概览 -->
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>角色概览</h3>
                </div>
                <div class="layui-card-body">
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="totalRoles">0</div>
                                <div class="stat-label">总角色数</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="enabledRoles">0</div>
                                <div class="stat-label">启用角色</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="adminRoles">0</div>
                                <div class="stat-label">管理角色</div>
                            </div>
                        </div>
                        <div class="layui-col-md3">
                            <div class="stat-item">
                                <div class="stat-value" id="disabledRoles">0</div>
                                <div class="stat-label">禁用角色</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 角色列表 -->
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <div class="role-header">
                        <h3 class="role-title">角色列表</h3>
                        <div class="role-actions">
                            <button class="layui-btn layui-btn-normal" onclick="addRole()">
                                <i class="layui-icon layui-icon-add-1"></i> 添加角色
                            </button>
                            <button class="layui-btn layui-btn-primary" onclick="refreshTable()">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-card-body">
                    <!-- 搜索表单 -->
                    <div class="search-form">
                        <div class="layui-form">
                            <div class="search-inline">
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 70px;">角色名称</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" name="searchRoleName" class="layui-input" placeholder="请输入角色名称">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 50px;">状态</label>
                                    <div class="layui-input-inline" style="width: 120px;">
                                        <select name="searchStatus">
                                            <option value="">全部</option>
                                            <option value="1">启用</option>
                                            <option value="0">禁用</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn" onclick="searchRoles()">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button class="layui-btn layui-btn-primary" onclick="resetSearch()">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 数据表格 -->
                    <div class="table-container">
                        <table class="layui-hide" id="roleTable" lay-filter="roleTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<!-- 操作按钮模板 -->
<script type="text/html" id="roleBarDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="permissions">权限配置</a>
    {{# if(d.id != 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    {{# } }}
</script>

{include file="layout/layui_footer" /}

<script>
layui.use(['table', 'form', 'layer', 'tree'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var tree = layui.tree;

    // 初始化表格
    table.render({
        elem: '#roleTable',
        url: '/admin/settings/getRoleList',
        height: 'full-200',
        page: true,
        loading: true,
        parseData: function(res) {
            // 更新统计数据
            if (res.data && res.data.length > 0) {
                updateStats(res.data, res.count);
            }
            return {
                "code": res.code,
                "msg": res.msg,
                "count": res.count,
                "data": res.data
            };
        },
        cols: [[
            {field: 'role_name', title: '角色名称', width: 120},
            {field: 'role_code', title: '角色代码', width: 120},
            {field: 'description', title: '角色描述', width: 200},
            {field: 'user_count', title: '用户数量', width: 100, align: 'center'},
            {field: 'permission_count', title: '权限数量', width: 100, align: 'center'},
            {field: 'status', title: '状态', width: 80, templet: function(d){
                return d.status == 1 ? '<span style="color: #5FB878;">启用</span>' : '<span style="color: #FF5722;">禁用</span>';
            }},
            {field: 'sort_order', title: '排序', width: 80, align: 'center'},
            {field: 'created_at', title: '创建时间', width: 160},
            {title: '操作', width: 220, toolbar: '#roleBarDemo'}
        ]]
    });

    // 监听工具条
    table.on('tool(roleTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            editRole(data.id);
        } else if(obj.event === 'del'){
            deleteRole(data.id, data.role_name);
        } else if(obj.event === 'permissions'){
            configPermissions(data.id, data.role_name);
        }
    });

    // 更新统计数据
    function updateStats(data, total) {
        var enabled = 0, admin = 0, disabled = 0;
        
        data.forEach(function(role) {
            if (role.status == 1) enabled++;
            if (role.status == 0) disabled++;
            if (role.role_code.indexOf('admin') >= 0) admin++;
        });
        
        $('#totalRoles').text(total);
        $('#enabledRoles').text(enabled);
        $('#adminRoles').text(admin);
        $('#disabledRoles').text(disabled);
    }

    // 搜索角色
    window.searchRoles = function() {
        table.reload('roleTable', {
            where: {
                role_name: $('input[name="searchRoleName"]').val(),
                status: $('select[name="searchStatus"]').val()
            }
        });
    };

    // 重置搜索
    window.resetSearch = function() {
        $('input[name="searchRoleName"]').val('');
        $('select[name="searchStatus"]').val('');
        form.render('select');
        table.reload('roleTable', {
            where: {}
        });
    };

    // 刷新表格
    window.refreshTable = function() {
        table.reload('roleTable');
    };

    // 添加角色
    window.addRole = function() {
        showRoleForm('添加角色', {});
    };

    // 编辑角色
    window.editRole = function(id) {
        $.get('/admin/settings/getRoleDetail', {id: id}, function(res) {
            if (res.code === 0) {
                showRoleForm('编辑角色', res.data);
            } else {
                layer.msg('获取角色信息失败：' + res.msg, {icon: 2});
            }
        });
    };

    // 显示角色表单
    function showRoleForm(title, role) {
        var isEdit = role.id ? true : false;
        var html = '<div style="padding: 20px;">' +
            '<form class="layui-form" lay-filter="roleForm">' +
            (isEdit ? '<input type="hidden" name="id" value="' + role.id + '">' : '') +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色名称 <span style="color:red;">*</span></label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="role_name" lay-verify="required" placeholder="请输入角色名称" class="layui-input" value="' + (role.role_name || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色代码 <span style="color:red;">*</span></label>' +
                '<div class="layui-input-block">' +
                    '<input type="text" name="role_code" lay-verify="required" placeholder="请输入角色代码(英文)" class="layui-input" value="' + (role.role_code || '') + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色描述</label>' +
                '<div class="layui-input-block">' +
                    '<textarea name="description" placeholder="请输入角色描述" class="layui-textarea">' + (role.description || '') + '</textarea>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">排序</label>' +
                '<div class="layui-input-block">' +
                    '<input type="number" name="sort_order" placeholder="请输入排序（数字越小越靠前）" class="layui-input" value="' + (role.sort_order || 0) + '">' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">状态</label>' +
                '<div class="layui-input-block">' +
                    '<select name="status">' +
                        '<option value="1" ' + (role.status == 1 ? 'selected' : '') + '>启用</option>' +
                        '<option value="0" ' + (role.status == 0 ? 'selected' : '') + '>禁用</option>' +
                    '</select>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<div class="layui-input-block">' +
                    '<button type="submit" class="layui-btn" lay-submit lay-filter="submitRole">保存</button>' +
                    '<button type="reset" class="layui-btn layui-btn-primary">重置</button>' +
                '</div>' +
            '</div>' +
            '</form>' +
            '</div>';

        layer.open({
            type: 1,
            title: title,
            content: html,
            area: ['500px', '550px'],
            success: function(layero, index) {
                form.render();
                
                // 监听表单提交
                form.on('submit(submitRole)', function(data) {
                    var url = isEdit ? '/admin/settings/editRole' : '/admin/settings/addRole';
                    
                    $.post(url, data.field, function(res) {
                        if (res.code === 0) {
                            layer.msg(res.msg, {icon: 1});
                            layer.close(index);
                            table.reload('roleTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    });
                    
                    return false;
                });
            }
        });
    }

    // 删除角色
    window.deleteRole = function(id, roleName) {
        layer.confirm('确定要删除角色 "' + roleName + '" 吗？', function(index) {
            $.post('/admin/settings/deleteRole', {id: id}, function(res) {
                if (res.code === 0) {
                    layer.msg(res.msg, {icon: 1});
                    table.reload('roleTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
                layer.close(index);
            });
        });
    };

    // 配置权限
    window.configPermissions = function(roleId, roleName) {
        $.when(
            $.get('/admin/settings/getPermissionTree'),
            $.get('/admin/settings/getRolePermissions', {role_id: roleId})
        ).done(function(treeRes, permRes) {
            if (treeRes[0].code === 0 && permRes[0].code === 0) {
                showPermissionConfig(roleId, roleName, treeRes[0].data, permRes[0].data);
            } else {
                layer.msg('获取权限数据失败', {icon: 2});
            }
        });
    };

    // 显示权限配置弹窗
    function showPermissionConfig(roleId, roleName, permissionTree, selectedIds) {
        var html = '<div style="padding: 20px;">' +
            '<div class="layui-form">' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">角色名称：</label>' +
                '<div class="layui-input-block" style="line-height: 38px;">' + roleName + '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<label class="layui-form-label">选择权限：</label>' +
                '<div class="layui-input-block">' +
                    '<div id="permissionTree" class="permission-tree"></div>' +
                '</div>' +
            '</div>' +
            '<div class="layui-form-item">' +
                '<div class="layui-input-block">' +
                    '<button type="button" class="layui-btn" onclick="savePermissions(' + roleId + ')">保存配置</button>' +
                    '<button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>' +
                '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        layer.open({
            type: 1,
            title: '权限配置 - ' + roleName,
            content: html,
            area: ['600px', '600px'],
            success: function(layero, index) {
                // 渲染权限树
                tree.render({
                    elem: '#permissionTree',
                    data: permissionTree,
                    showCheckbox: true,
                    id: 'permissionTreeDemo',
                    isJump: false,
                    click: function(obj) {
                        // 处理点击事件
                    }
                });
                
                // 设置选中状态
                setTimeout(function() {
                    tree.setChecked('permissionTreeDemo', selectedIds);
                }, 100);
                
                // 全局保存权限函数
                window.savePermissions = function(roleId) {
                    // 使用layui tree的getChecked方法获取选中的节点
                    var checkedData = tree.getChecked('permissionTreeDemo');
                    var permissionIds = [];
                    
                    // 调试信息
                    console.log('权限树选中数据:', checkedData);
                    
                    // 如果checkedData是数组，直接遍历
                    if (Array.isArray(checkedData)) {
                        checkedData.forEach(function(item) {
                            permissionIds.push(item.id);
                            console.log('选中权限:', item.id, item.title);
                        });
                    } else {
                        // 如果不是数组，尝试从树结构中获取所有选中的节点
                        var treeData = layui.tree.getChecked('permissionTreeDemo');
                        
                        // 递归获取所有选中的权限ID（包括子节点）
                        function getCheckedIds(nodes) {
                            if (!nodes || !Array.isArray(nodes)) return;
                            nodes.forEach(function(node) {
                                if (node.checked) {
                                    permissionIds.push(node.id);
                                    console.log('选中权限:', node.id, node.title);
                                }
                                if (node.children && node.children.length > 0) {
                                    getCheckedIds(node.children);
                                }
                            });
                        }
                        
                        // 如果上面的方法还是不行，尝试直接从DOM获取选中状态
                        if (permissionIds.length === 0) {
                            $('#permissionTree input[type="checkbox"]:checked').each(function() {
                                var $checkbox = $(this);
                                var $node = $checkbox.closest('[data-id]');
                                if ($node.length > 0) {
                                    var nodeId = $node.attr('data-id');
                                    if (nodeId && permissionIds.indexOf(nodeId) === -1) {
                                        permissionIds.push(nodeId);
                                        console.log('从DOM获取选中权限:', nodeId);
                                    }
                                }
                            });
                        }
                    }
                    
                    console.log('最终权限ID数组:', permissionIds);
                    
                    // 如果没有选中任何权限，也要发送请求（清空权限）
                    $.post('/admin/settings/assignPermissions', {
                        role_id: roleId,
                        permission_ids: permissionIds
                    }, function(res) {
                        console.log('服务器响应:', res);
                        if (res.code === 0) {
                            layer.msg(res.msg, {icon: 1});
                            layer.close(index);
                            table.reload('roleTable');
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }).fail(function(xhr, status, error) {
                        console.error('请求失败:', xhr.responseText);
                        layer.msg('请求失败，请检查网络连接', {icon: 2});
                    });
                };
            }
        });
    }
});
</script> 